﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Eye.Logic;

namespace The_Eye
{
    public partial class DBNotes : Form
    {
        User currentUser = null;

        public DBNotes()
        {
            InitializeComponent();
            var users = UsersService.GetUsers();
            try
            {
                dgvUsers.RowCount = users.Count;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                dgvUsers.RowCount = 1;
            }
            foreach (var user in users)
            {
                dgvUsers.Rows.Add(user.First_Name, user.Second_Name, user.Midl_Name, user.Passport);
            }
        }

        private void dgvUsers_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                User user = new User();
                user.Passport = e.Row.Cells["Passport"].Value.ToString();
                UsersService.RemoveUser(user);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ahtung!!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvUsers_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            currentUser = UsersService.GetUser(dgvUsers.Rows[e.RowIndex].Cells["Passport"].Value.ToString());
        }

        private void dgvUsers_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            User user = new User();
            int index = e.RowIndex;
            user.First_Name = dgvUsers.Rows[index].Cells["FirstName"].Value.ToString();
            user.Second_Name = dgvUsers.Rows[index].Cells["SecondName"].Value.ToString();
            user.Midl_Name = dgvUsers.Rows[index].Cells["MidlName"].Value.ToString();
            user.Passport = dgvUsers.Rows[index].Cells["Passport"].Value.ToString();
            if (currentUser != null)
            {
                if (!currentUser.First_Name.Equals(user.First_Name) | !currentUser.Second_Name.Equals(user.Second_Name) |
                    !currentUser.Midl_Name.Equals(user.Midl_Name) | !currentUser.Passport.Equals(user.Passport))
                {
                    user.Id = currentUser.Id;
                    UsersService.UpdateUser(user);
                }
            }
            else
            {
                MessageBox.Show("Seavin changes fault", "Ahtung!!!!", MessageBoxButtons.OK);
            }
        }

    }
}
